package com.miplus.ccrm.core.service.xsky;

import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.*;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.miplus.ccrm.common.JPubUtils;
import com.miplus.ccrm.core.service.aiqm.TRecorderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Arrays;

@Slf4j
@Service
public class XSkyService {
    @Value("${xsky.aws.bucketName}")
    private String aws_bucketName;

    @Value("${xsky.tempfileDir}")
    private String cti_tempfileDir;
    @Value("${ccrm.recfile.url}")
    private String rec_fileurl;

    @Value("${uploadfiles.filesize}")
    private Integer uploadFileSize;
    private final TRecorderService recorderService;
    private final AmazonS3 s3Client;

    @Autowired
    public XSkyService(AmazonS3 s3,TRecorderService recorderService)
    {
        log.info("XSkyService.build:{}",s3);
        this.s3Client=s3;
        this.recorderService=recorderService;
    }

    public void OnPlayRecord(String skyid, HttpServletResponse response) {
        try {
            log.info("OnPlayRecord({}):{}",aws_bucketName,skyid);

            if(JPubUtils.IsEmpty(skyid)||JPubUtils.IsEqual(skyid,"-1"))
                return;

            int maxrecsize=1024*1024*uploadFileSize; //50M
            // 调用OSS服务下载文件,下载文件方式
            //String localPath=cti_tempfileDir+skyid;
            //ObjectMetadata data=s3Client.getObject(new GetObjectRequest(aws_bucketName, skyid), new File(localPath));
            //log.info("OnPlayRecord:{},length={}",localPath,data.getContentLength());

            S3Object fullObject=s3Client.getObject(aws_bucketName, skyid);
            log.info("OnPlayRecord({}):{}",skyid,fullObject);

            S3ObjectInputStream s3is=fullObject.getObjectContent();
            byte[] read_buf=new byte[2048];
            byte[] read_bufall=new byte[1028*1024*5];
            int read_len=0;
            int read_total=0;
            int copy_pos=0;
            while ((read_len=s3is.read(read_buf))>0){
                read_total+=read_len;
                if(read_total>read_bufall.length) {
                    //动态扩容大小
                    read_bufall = Arrays.copyOf(read_bufall,read_total);
                }
                System.arraycopy(read_buf,0,read_bufall,copy_pos,read_len);
                copy_pos+=read_len;
                if(read_total>maxrecsize){
                    log.warn("OnPlayRecord({}):too many break.",skyid);
                    break;
                }
            }
            log.info("OnPlayRecord({}):Size={},buflength={}",skyid,read_total,read_bufall.length);
            response.addHeader("Content-Type","audio/mpeg;charset=utf-8");
            response.addHeader("Content-Length",read_total+"");
            ServletOutputStream out=response.getOutputStream();
            out.write(read_bufall,0,read_total);
            out.flush();
            out.close();

            s3is.close();

            log.info("OnPlayRecord({}):Ok",skyid);

        } catch (Exception e) {
            log.error("OnPlayRecord.Err:",e);
        }
    }

    public void OnPlayFile(String skyid, HttpServletResponse response)
    {
        String urlbody=rec_fileurl;
        String recipaddr=recorderService.getRecordIPAddr(skyid);
//        if(JPubUtils.IsEqual(recipaddr,"-1")){
//            log.warn("OnPlayLocalRecord({}).NoFind Record",skyid);
//            return;
//        }
//        log.info("OnPlayLocalRecord({}).IPAddr={}",skyid,recipaddr);
//        if(JPubUtils.IsNotEmpty(recipaddr)){
//            String port="9510";
//            if(JPubUtils.IsNotEmpty(rec_fileurl)){
//                port=rec_fileurl.split(":")[2];
//            }
//            urlbody="http://"+recipaddr+":"+port;
//        }

//        if(!urlbody.endsWith("/")) urlbody=urlbody+"/";
//        urlbody=urlbody+"file/playRecord?callid="+skyid;
        urlbody=urlbody+recipaddr;
        try {
            log.info("OnPlayLocalRecord:{}",urlbody);
            HttpResponse<InputStream> inputResponse = Unirest.get(urlbody).asBinary();
            InputStream fis = inputResponse.getBody();
            response.addHeader("Content-Type","audio/mpeg;charset=utf-8");
            ServletOutputStream out = response.getOutputStream();
            int len_l = 0,totalcnt=0;
            byte[] buf = new byte[1024];
            while ((len_l = fis.read(buf)) != -1) {
                totalcnt+=len_l;
                out.write(buf, 0, len_l);
            }
            out.flush();
            out.close();
            fis.close();

            log.info("OnPlayLocalRecord.totalcnt={}",totalcnt);
        } catch (Exception e) {
            log.error("OnPlayLocalRecord.Err:",e);
        }
    }

    private boolean fileExists(String keyid) {
        return s3Client.doesObjectExist(aws_bucketName, keyid);
    }

    public void DownloadFile(String skyid, HttpServletResponse response) {
        try {
            log.info("DownloadFile({}):{}",skyid,aws_bucketName);

            if(JPubUtils.IsEmpty(skyid)||JPubUtils.IsEqual(skyid,"-1"))
                return;

            // 调用OSS服务下载文件,下载文件方式
            // s3Client.getObject(new GetObjectRequest(aws_bucketName, skyid), new File(localPath));

            int maxfilesize=1024*1024*uploadFileSize; //50M
            response.addHeader("Content-Type","application/octet-stream;charset=utf-8");
            response.addHeader("Content-Disposition","attachment; filename="+skyid);
            ServletOutputStream out=response.getOutputStream();

            S3Object fullObject=s3Client.getObject(aws_bucketName, skyid);
            log.info("DownloadFile({}):{}",skyid,fullObject);

            S3ObjectInputStream s3is=fullObject.getObjectContent();
            byte[] read_buf=new byte[2048];
            int read_len=0;
            int read_total=0;
            while ((read_len=s3is.read(read_buf))>0){
                read_total+=read_len;
                out.write(read_buf,0,read_len);
                if(read_total>maxfilesize){
                    log.warn("DownloadFile({}):too many break.",skyid);
                    break;
                }
            }
            log.info("DownloadFile({}):Size={}",skyid,read_total);

            s3is.close();
            out.flush();
            out.close();

            log.info("DownloadFile({}):Ok",skyid);

        } catch (Exception e) {
            log.error("DownloadFile.Err:",e);
        }
    }

    public boolean UploadFile(String keyid, String localPath) {
        try {
            log.info("UploadFile({}) From {}",keyid,localPath);
            File file = new File(localPath);
            PutObjectResult result=s3Client.putObject(aws_bucketName, keyid, file);

            log.info("UploadFile({}) OK:{}",keyid,result);

            return true;
        } catch (Exception e) {
            log.error("UploadFile.Err:",e);
            return false;
        }
    }

    public boolean UploadFile(String keyid, File file) {

        log.info("UploadFile({}) From file",keyid);

        PutObjectResult result=s3Client.putObject(aws_bucketName, keyid, file);

        log.info("UploadFile({}) OK:{}",keyid,result);

        return true;
    }
}
